package ca.llsutherland.squash.domain.helper;

import ca.llsutherland.squash.domain.Administrator;
import ca.llsutherland.squash.domain.Clock;
import ca.llsutherland.squash.domain.Greeting;
import ca.llsutherland.squash.exceptions.ValidationException;
import ca.llsutherland.squash.utils.ErrorConstants;

public class GreetingsHelper {

    public static Greeting createUnpersistedGreeting(String message, Clock dateCreated, Clock dateUpdated, Clock displayDate, Clock removeDate, Administrator createdBy) {
        Greeting greeting = createUnpersistedGreeting(message, dateCreated, dateUpdated, displayDate, removeDate);
        greeting.setCreatedBy(createdBy);
        return greeting;
    }

    private static Greeting createUnpersistedGreeting(String greeting, Clock dateCreated, Clock dateUpdated, Clock displayDate, Clock removeDate) {
        Greeting item = new Greeting();
        item.setMessage(greeting);
        item.setDateCreated(dateCreated);
        item.setDateUpdated(dateUpdated);
        item.setDisplayDate(displayDate);
        item.setRemoveDate(removeDate);
        return item;
    }
    
    public static Greeting createNewGreeting(String message, Clock dateCreated, Clock dateUpdated, Clock displayDate, Clock removeDate, Administrator createdBy, Long id) {
        Greeting greeting = createUnpersistedGreeting(message, dateCreated, dateUpdated, displayDate, removeDate, createdBy);
        greeting.setId(id);
        return greeting;
    }

    public static void assertNewValid(Greeting greeting) {
        DomainObjectHelper.assertNotNullWithErrorMessage(greeting, ErrorConstants.NULL_GREETING_ITEM_ERROR);
        DomainObjectHelper.assertNonBlankStringWithErrorMessage(greeting.getMessage(), ErrorConstants.BLANK_STRING_ERROR);
        assertNewsLength(greeting);
        assertAdministratorNotNull(greeting);
        assertDisplayRemoveDatesValid(greeting);
    }

    private static void assertDisplayRemoveDatesValid(Greeting greeting) {
        if(greeting.getDisplayDate() == null || greeting.getRemoveDate() == null) {
            throw new ValidationException(ErrorConstants.NULL_DATE_ERROR);
        }
        if(!greeting.getDisplayDate().isBefore(greeting.getRemoveDate())) {
            throw new ValidationException(ErrorConstants.INVALID_GREETING_DATES);
        }
    }

    private static void assertAdministratorNotNull(Greeting greeting) {
        if(greeting.getCreatedBy() == null) {
            throw new ValidationException(ErrorConstants.NULL_ADMINISTRATOR_ERROR);
        }
    }

    private static void assertNewsLength(Greeting greeting) {
        if(greeting.getMessage().length() > 1000) {
            throw new ValidationException(ErrorConstants.GREETING_TOO_LONG_ERROR);
        }
    }



}
